<template>
  <div>
    <AModal
      v-bind="$attrs"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="formRef" :model="form" auto-label-width>
        <AFormItem
          field="userPassword"
          label="新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
          :validate-trigger="['change', 'input', 'blur']"
        >
          <AInputPassword v-model="form.userPassword"></AInputPassword>
        </AFormItem>
        <AFormItem
          field="newPassword"
          label="确认密码"
          :rules="[{ required: true, message: '请输入密码' }]"
          :validate-trigger="['change', 'input', 'blur']"
        >
          <AInputPassword v-model="form.newPassword"></AInputPassword>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { editPassword } from '@renderer/api/user'
import { useUserStore } from '@renderer/store'

const emit = defineEmits(['update:visible', 'reload'])
const userInfo = useUserStore().localUserInfo
const form = ref({
  userPassword: '',
  newPassword: '',
  userId: userInfo.userId
})
const formRef = ref()

const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors) => {
        if (!errors) {
          if (form.value.userPassword !== form.value.newPassword) {
            Message.error('两次密码不一致')
            return
          }
          editPassword(form.value).then(() => {
            Message.success('修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    case 'open':
      break
    case 'cancel':
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    default:
      break
  }
}
</script>
<style scoped></style>
